package com.ruoyi.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESDemo {
    private final static String Encod = "UTF8";
    public static String decrypt(String ciphertext, String key) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(ciphertext) || StringUtils.isBlank(key)) {
            throw new RuntimeException("AES解密失败, 参数有误. ciphertext: " + ciphertext + ", key: " + key);
        }
        byte[] keyBytes = key.getBytes(Encod);
        byte[] dataBytes = Base64.decodeBase64(ciphertext);
        byte[] keyBytesDecrypt = decrypt(dataBytes, keyBytes);
        return new String(keyBytesDecrypt, Encod);
    }
    public static byte[] decrypt(byte[] value, byte[] key) throws Exception {
        if (key.length != 16) {
            throw new RuntimeException("AES解密失败, 密钥不是128位");
        }
        Cipher cipher = Cipher.getInstance("AES");
        SecretKey keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        return cipher.doFinal(value);
    }

    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        if (key.length != 16) {
            throw new RuntimeException("AES加密失败, 密钥不是128位");
        }
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return cipher.doFinal(data);
    }
    public static String encrypt(String data, String key) throws Exception {
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            throw new RuntimeException("AES加密失败, 参数有误. data: " + data + ", key: " + key);
        }
        byte[] keyBytes = key.getBytes(Encod);
        byte[] dataBytes = data.getBytes(Encod);
        byte[] encryptBytes = encrypt(dataBytes, keyBytes);
        return new String(Base64.encodeBase64(encryptBytes));
    }

    public static void main(String[] args) throws Exception {
        String key="w3asd4dsdw35hvjs";
        String str = "{\"phoneNumber\":\"13711111111\",\"customerName\":\"姓名\",\"age\":20,\"sex\":1,\"city\":\"深圳\",\"creditLimit\":200000,\"channel\":\"chan\",\"hasHouse\":1,\"hasCar\":1,\"hasCredit\":1,\"hasPolicy\":1,\"hasSocial\":1,\"hasAccumulationFund\":1}";
        String f = encrypt(str,key);
        System.out.println(f);
        //输出结果
        // rNZblcA8OZ3piMW8aObUAc6viXhH/9KTRUeQ4A35Cnyha4WixKbvb1mfRo8T9sov6JAt+kpBCtY4Bv+AHaguSBVHXRJ899VsJu8mj0om1XfpZncqvFJhrFyUWMHKAspGCDHcA11N9RgxPNWWexqEiRQ3Z3OlTD6xZ+3bgbjv/jHW/66Ci5VuukvIb/5r2jBwlFk4Qrj/n5dYCTwyE44r/lZEuUsUC52XhF+s6uPv7H0R1Gmo31yvdptF5r9EvyQ1GpgmZofdcZzUWvchfv2eHXCbtF60F/M2VvbfwsSx5jg=
    }
}
